<template>
  <div>
    <el-row :gutter="20" type="flex" justify="space-around" class="center-box">
      <el-col :span="10" class="float-card">
        <!--操作盒子-->
        <el-row :gutter="20" type="flex" justify="center" align="middle" class="filter-box">
          <el-col :span="0.1">
            <el-card shadow="hover">
              <h2>企业行业</h2>
              <el-cascader
                  :props="{ checkStrictly: true }"
                  v-model="industryChoose"
                  placeholder="选择行业(可搜索)"
                  :options="industryOption"
                  filterable
                  clearable
                  @change="industryHandler"
              >
              </el-cascader>
            </el-card>
          </el-col>
          <el-col :span="0.1">
            <el-card shadow="hover">
              <h2>企业地区</h2>
              <el-cascader
                  :props="{ checkStrictly: true }"
                  v-model="locationChoose"
                  placeholder="选择地区(可搜索)"
                  :options="locationsOption"
                  filterable
                  clearable
                  @change="locationsHandler"
              >
              </el-cascader>
            </el-card>
          </el-col>
          <el-col :span="0.1">
            <el-card shadow="hover">
              <h2>邮件内容</h2>
              <el-cascader
                  placeholder="选择模板(可搜索)"
                  :options="templateOptions"
                  v-model="sendTemplate"
                  filterable
                  ref="templateRef"
              >
              </el-cascader>
            </el-card>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center" align="middle">
          <el-col :span="0.1">
            <el-button @click="sendEmail" type="primary" circle class="send-btn">
              发送
            </el-button>
          </el-col>
        </el-row>
        <!--消息-->
        <el-alert
            class="message-alert"
            :title="prompt"
            type="info"
            effect="dark"
            :closable="false"
            center>
        </el-alert>
      </el-col>
      <el-col :span="13" class="float-card">
        <el-alert
            :title="`发送队列(${server.sendQueue.length})`"
            type="warning"
            center
            :closable="false"
            effect="dark">
        </el-alert>
        <el-table
            :data="server.sendQueue"
            height="400"
            empty-text="当前暂无队列"
            :align="'center'"
        >
          <el-table-column
              type="index"
              width="20">
          </el-table-column>
          <el-table-column
              prop="title"
              label="邮件标题"
              width="120">
          </el-table-column>
          <el-table-column
              label="已发送数量"
              width="100">
            <template v-slot="scope">
              <el-tag v-if="scope.row.mailSendStatus">
                {{ scope.row.mailSendStatus.mailSucceed + scope.row.mailSendStatus.mailFail }}
              </el-tag>
              <el-tag type="info" v-else>
                -
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
              label="总数量"
              width="100">
            <template v-slot="scope">
              <el-tag v-if="scope.row.mailSendStatus">
                {{ scope.row.list.length }}
              </el-tag>
              <el-tag type="info" v-else>
                -
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
              label="开始日期">
            <template v-slot="scope">
              {{ scope.row.beginDate | dateFormatter }}
            </template>
          </el-table-column>
          <el-table-column
              label="进度">
            <template v-slot="scope">
              <el-progress
                  v-if="scope.row.mailSendStatus"
                  :percentage="compPercentage(scope.row.mailSendStatus)">
              </el-progress>
              <el-tag type="warning" v-else>
                等待中
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {mapActions, mapGetters} from "vuex";
import {Message} from "element-ui";
import Vue from "vue";

export default {
  name: "SendEmail",
  data() {
    return {
      industryOption: [],
      locationsOption: [],
      prompt: '',
      industryChoose: [],
      locationChoose: [],
      sendList: [],
      //分页信息对象
      pageInfo: {
        //当前页
        offset: 1,
        //当前页数据量
        limit: 300,
        //城市
        city: '',
        //省份
        province: '',
        //行业关键字
        scope: ''
      },
      total: 0,
      emailInfo: {
        title: '',
        message: '',
        list: []
      },
      templateOptions: [],
      sendTemplate: [],
      filterBox: {},
      //发送时组装的对象
      mailCarrier: {
        //邮件标题
        mailTitle: '',
        //邮件内容
        mailContent: '',
        //附件路径
        appendix: '',
        //分页对象
        myPageInfo: {}
      }
    }
  }, mounted() {
    this.initializeNavigation().then(() => {
      //对行业数据进行封装
      this.industryOption = [];
      for (let i = 0; i < this.industry.length; i++) {
        let industryElement = this.industry[i];
        //value  label children
        let childrenIndustry = [];
        for (let j = 0; j < industryElement.subIndustry.length; j++) {
          childrenIndustry.push({
            value: industryElement.subIndustry[j].name,
            label: industryElement.subIndustry[j].name
          })
        }
        this.industryOption.push({
          value: industryElement.name,
          label: industryElement.name,
          children: childrenIndustry
        })
      }
      this.locationsOption = [];
      //对地区数据封装
      for (let i = 0; i < this.locations.length; i++) {
        let location = this.locations[i];
        let city = [];
        if (location.city.length === 1) {
          for (let j = 0; j < location.city[0].region.length; j++) {
            city.push({
              label: location.city[0].region[j].name,
              value: location.city[0].region[j].name
            })
          }
        } else {
          for (let j = 0; j < location.city.length; j++) {
            city.push({
              label: location.city[j].name,
              value: location.city[j].name
            })
          }
        }
        this.locationsOption.push({
          value: location.name,
          label: location.name,
          children: city
        })
      }
    });
    //判断路由是否有传入参数
    let query = this.$route.query;
    if (query.filterBox) {
      this.filterBox = JSON.parse(query.filterBox.toString());
      this.industryChoose = [];
      this.industryChoose.push(this.filterBox.largeTypeName);
      if (this.filterBox.subTypeName) {
        this.industryChoose.push(this.filterBox.subTypeName);
      }
      this.locationChoose = [];
      this.locationChoose.push(this.filterBox.provinces);
      if (this.filterBox.city) {
        this.locationChoose.push(this.filterBox.city);
      }
      this.pageInfo.scope = this.filterBox.subTypeName;
      this.pageInfo.city = this.filterBox.city;
      this.pageInfo.province = this.filterBox.provinces;
    }
    this.getRecipients();
    this.getTemplates();
    //判断当前是否可以发送
  }, methods: {
    ...mapActions({initializeNavigation: 'navigation/initializeNavigation'}),
    async getRecipients() {
      let {data: rs} = await this.axios.get(`companydata/findByPCIdLimit`, {params: this.pageInfo, timeout: 30000});
      this.total = rs.content.findByPCIdLimit.total;
      this.prompt = `当前总共查询到${this.total}个企业`;
    },
    industryHandler(val) {
      if (val.length > 0) {
        this.pageInfo.scope = val[1];
      } else {
        this.pageInfo.scope = '';
      }
      this.getRecipients();
    }, locationsHandler(val) {
      if (val.length > 0) {
        this.pageInfo.province = val[0];
        if (val[1].indexOf("市") > 0) {
          this.pageInfo.city = val[1].substring(0, val[1].indexOf("市"));
        } else {
          this.pageInfo.city = val[1];
        }
      } else {
        this.pageInfo.province = '';
        this.pageInfo.city = '';
      }
      this.getRecipients();
    },
    //获得模板选项
    async getTemplates() {
      let {data: rs} = await this.axios.get('emailcontent/getEmailTemplate');
      this.templateOptions = [];
      for (let i = 0; i < rs.content.templateOptions.length; i++) {
        this.templateOptions.push({
          label: rs.content.templateOptions[i].emailTitle,
          value: rs.content.templateOptions[i].emailContent
        });
      }
    },
    //发送邮件
    sendEmail() {
      // 发送前先验证一下条件
      if (this.sendTemplate.length === 0) {
        Message.warning('选择提前导入的模板,客户才能看到内容哦!');
        return false;
      } else if (this.total === 0) {
        Message.warning('当前查询的数量不足以发送邮件!');
        return false;
      }
      this.$confirm(`本次可发送${this.total}个企业,确认发送?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //获得全部查询的集合
        this.mailCarrier.mailContent = this.sendTemplate[0];
        this.mailCarrier.mailTitle = this.$refs['templateRef'].inputValue;
        this.mailCarrier.myPageInfo = this.pageInfo;
        this.axios.post('emailPushModule/MassSendMail', this.mailCarrier);
      }).catch(() => {
        Message.warning('已取消发送!');
      });
    },
    //计算进度
    compPercentage(status) {
      //如果正在发送,但成功数量和失败数量都为0就会导致计算无意义报错
      if (status.flag) {
        return 100;
      } else if (status.count > 0) {
        return Number(((status.mailSucceed + status.mailFail) / status.count * 100).toFixed(2));
      }
      return 0;
    }
  }, computed: {
    ...mapGetters({
      industry: 'navigation/getIndustry',
      locations: 'navigation/getLocations',
      server: 'server/getCurrentServer'
    })
  }, filters: {
    dateFormatter(val) {
      return new Date(val);
    }
  }
}
</script>

<style scoped>
@media screen and (max-width: 1250px) {
  .center-box {
    flex-flow: column wrap;
    align-items: center;
    justify-content: space-around;
  }

  .float-card {
    width: 100%;
  }

  .float-card + .float-card {
    margin-top: 10px;
  }
}

@media screen and (max-width: 680px) {
  .filter-box {
    flex-flow: column wrap;
    align-items: center;
    justify-content: space-around;
  }

  .filter-box > .el-col + .el-col {
    margin-top: 10px;
  }
}

.message-alert {
  margin-top: 10px;
}

.el-row + .el-row {
  margin-top: 20px;
}

.send-btn {
  width: 200px;
  height: 200px;
  font-weight: bolder;
  font-size: 1.5rem;
}
</style>